package org.lakeside.outreach.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;

public class OutreachManager implements EntryPoint {
	
	private static OutreachManager singleton;
	
	public static OutreachManager get() {
		return singleton;
	}
	
	private TopPanel topPanel = new TopPanel();
	private VerticalPanel mainPanel = new VerticalPanel();
	private HorizontalPanel hPanel = new HorizontalPanel();
	private ProjectListPanel projectListPanel = new ProjectListPanel();
	private ProjectDetailPanel projectDetailPanel = new ProjectDetailPanel();
	private final ProjectServiceAsync projectService = GWT.create(ProjectService.class); 
	
	//Login details
	private LoginInfo loginInfo = null;
	private VerticalPanel loginPanel = new VerticalPanel();
	private Label loginLabel = new Label("Please sign in to your google account to access the Lakeside CDC Outreach Manager.");
	private Anchor signInLink = new Anchor("Sign In");

	public void onModuleLoad() {
		LoginServiceAsync loginService = GWT.create(LoginService.class);
		loginService.login(GWT.getHostPageBaseURL(), new AsyncCallback<LoginInfo>() {

			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onSuccess(LoginInfo result) {
				loginInfo = result;
				if(loginInfo.isLoggedIn()) {
					loadOutreachManager();
				} else {
					loadLogin();
				}
			}
			
		});
	}
	
	private void loadLogin() {
		// Assemble login panel
		signInLink.setHref(loginInfo.getLoginUrl());
		loginPanel.add(loginLabel);
		loginPanel.add(signInLink);
		RootPanel.get().add(loginPanel);
	}
	
	private void loadOutreachManager() {
		singleton = this;
		
		topPanel.setWidth("100%");
		
		hPanel.add(projectListPanel);
		hPanel.add(projectDetailPanel);
		projectDetailPanel.setWidth("95%");
		projectListPanel.setWidth("95%");
		hPanel.setWidth("100%");
		hPanel.setHeight("100%");
		hPanel.setCellWidth(projectDetailPanel, "50%");
		hPanel.setCellWidth(projectListPanel, "50%");
		
		mainPanel.add(topPanel);
		mainPanel.add(hPanel);
		
		mainPanel.setWidth("100%");
		mainPanel.setHeight("100%");
		
		// add main panel to root panel
		RootPanel.get().add(mainPanel);
	}
	
	public ProjectServiceAsync getProjectService() {
		return projectService;
	}
	
	public void reload() {
		loadOutreachManager();
	}
	
	public ProjectListPanel getProjectList() {
		return projectListPanel;
	}
	
	public ProjectDetailPanel getProjectDetailPanel() {
		return projectDetailPanel;
	}
}